﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Cms.Model;
using Portal.Utility;
using Portal.Web.Model;
using Portal.Core;
using dtSearch32Lib;
using DocumentSearchServiceModel;
using DocumentSearch32Lib;
using Portal.Systems.Model;
using Portal.Workflow.Bussiness;
using Portal.Cms.Utility;
using System.Data;
using Portal.Database.Service;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class AddCmsDocumentDataRenderBll
    {

        static string GetPlugInJavascript(string SiteId, string ParentDataId)
        {
            string ScriptText =
                "<input type=hidden id=txtParentDataId value=\"" + ParentDataId + "\">\r\n";
            //"<script language=javascript>\r\n" +

            //"</script>\r\n";
            return ScriptText;
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                //string GroupDataFolderId = (string)WebEnvironments.Request(SiteId, "GroupDataFolderId");


                //if(string.IsNullOrEmpty(GroupDataFolderId))GroupDataFolderId="";
                //string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                string ParentDataId = (string)WebEnvironments.Request(SiteId, "parent");
                string wfcId = (string)WebEnvironments.Request(SiteId, "wfc");
                if (string.IsNullOrEmpty(wfcId)) wfcId = WebConfig.WorkFlowId;
                string Html =
                    //GetPlugInJavascript(SiteId, ParentDataId) +
                    //"<input id=\"txtGroupDataFolderId\" value=\"" + GroupDataFolderId + "\" type=hidden>\r\n" +
                   DrawAddForm(SiteId, GroupDataId, wfcId).HtmlContent;

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut DrawAddForm(
            string SiteId,
            string GroupDataId,
            string wfcId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                WorkflowControlCls OWorkflowControl = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateWorkflowControlModel(SiteId, wfcId);
                WorkflowDefCls OWorkflowDef = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateWorkflowDefFromWorkflowControl(SiteId, wfcId);
                string DataLanguage = "";
                string WorkflowName = "";
                string WorkflowDefId = "";
                if (OWorkflowDef != null)
                {
                    WorkflowName = " - theo quy trình " + OWorkflowControl.Title;
                    WorkflowDefId = OWorkflowDef.WorkflowDefId;
                    DataLanguage = OWorkflowControl.DataLanguageCode;
                    //kiem tra xem role nay co quyen start quy trinh nay khong
                    bool Allow = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckAllowAccessWorkflow(SiteId, WebSessionUtility.GetCurrentLoginUser().RoleId, WorkflowDefId);
                    if (Allow == false) throw new Exception("Bạn không có quyền thao tác với quy trình này!");
                }
                else
                {
                    SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                }
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                //string StyleDisp = " style=\"display:none;\"";
                //if (OGroupData.ShowBody)
                //{
                //    StyleDisp = "";
                //}

                string BackScript = "javascript:window.open('DocumentInputData.aspx?gid=" + OGroupData.GroupDataId + "','_self');";
                string back = (string)WebEnvironments.Request(SiteId, "back");
                if (!string.IsNullOrEmpty(back))
                {
                    BackScript = "javascript:window.open('" + back + "','_self');";
                }

                string UploadHandler = "CmsUploadHandler.ashx";
                if (OGroupData.frkDataTypeId.Equals("document"))
                {
                    UploadHandler = "CmsUploadAttachFileHandler.ashx";
                }
                string NewDataId = System.Guid.NewGuid().ToString();
                string Html =
                     "<script language=javascript>\r\n " +

                    "  function ProcessExpandCollapse(Id)\r\n" +
                    "  {\r\n" +
                    "     if(document.getElementById(Id).className=='Collapsed')\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Expanded';\r\n" +
                    "     }\r\n" +
                    "     else\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Collapsed';\r\n" +
                    "     }\r\n" +
                    "  }\r\n" +

                    " function ClientDocReleaseChange()\r\n" +
                    " {\r\n" +
                    "      objSelectDocReleaseFrom = document.getElementById('drpSelectDocReleaseFrom');\r\n" +
                    "      SelectDocReleaseFrom = objSelectDocReleaseFrom.options[objSelectDocReleaseFrom.selectedIndex].value;\r\n" +


                    "      AjaxOut = Portal.Cms.Render.AddCmsDocumentDataRenderBll.ServerDocReleaseChange('" + SiteId + "', SelectDocReleaseFrom).value;\r\n" +

                    "      objSelectDocSigner = document.getElementById('drpSelectDocSigner');\r\n" +
                    "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='';\r\n" +
                    "      if(AjaxOut.Error)\r\n" +
                    "      {\r\n" +
                    "          alert(AjaxOut.InfoMessage);\r\n" +
                    "          return;\r\n" +
                    "      }\r\n" +
                    "      var oDocSignerClss = AjaxOut.RetObject; \r\n" +
                    "      objSelectDocSigner.innerHTML = ''; \r\n" +
                    "      for(var index = 0;index<  oDocSignerClss.length; index++)\r\n" +
                    "      {\r\n" +
                    "          objSelectDocSigner.options[objSelectDocSigner.options.length] = new Option(oDocSignerClss[index].DocSignerName,oDocSignerClss[index].DocSignerId ); \r\n" +
                    "      }\r\n" +
                    " }\r\n" +

                    " function CallSaveAddData()\r\n" +
                    " {\r\n" +
                    "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='Tiến hành cập nhật và đánh index tìm kiếm...';\r\n" +
                    "      setTimeout('RealCallSaveAddData()',10);\r\n" +
                    " }\r\n" +

                    "  function RealCallSaveAddData()\r\n" +
                    "  {\r\n" +
                    "      SiteId='" + SiteId + "';\r\n" +
                    "      GroupDataId='" + GroupDataId + "';\r\n" +
                    "      GroupDataFolderId='';//document.getElementById('txtGroupDataFolderId').value;\r\n" +
                    "      DataId=document.getElementById('txtDataId').value;\r\n" +
                    "      Alias = document.getElementById('txtAlias').value;\r\n" +//số văn bản
                    "      Subject = document.getElementById('txtSubject').value;\r\n" +//trích yếu
                    "      Description ='';// document.getElementById('txtDescription').value; \r\n" +//mô tả
                    "      UploadFile=document.getElementById('txtUploadFile').value;\r\n" +
                    "      ParentDataId='';//document.getElementById('txtParentDataId').value;\r\n" +

                    "      DocType='';\r\n" +
                    "      if(document.getElementById('drpSelectDocType')!=null)\r\n" +
                    "      {\r\n" +
                    "          DocType=document.getElementById('drpSelectDocType').value;\r\n" +
                    "      }\r\n" +

                    "      DocField='';\r\n" +
                    "      if(document.getElementById('drpSelectDocField')!=null)\r\n" +
                    "      {\r\n" +
                    "          DocField=document.getElementById('drpSelectDocField').value;\r\n" +
                    "      }\r\n" +

                    "      DocReleaseFrom='';\r\n" +
                    "      if(document.getElementById('drpSelectDocReleaseFrom')!=null)\r\n" +
                    "      {\r\n" +
                    "          DocReleaseFrom=document.getElementById('drpSelectDocReleaseFrom').value;\r\n" +
                    "      }\r\n" +
                    "      DocSigner='';\r\n" +
                    "      if(document.getElementById('drpSelectDocSigner')!=null)\r\n" +
                    "      {\r\n" +
                    "          DocSigner=document.getElementById('drpSelectDocSigner').value;\r\n" +
                    "      }\r\n" +

                    "      DocStatus='';\r\n" +
                    "      if(document.getElementById('drpSelectDocStatus')!=null)\r\n" +
                    "      {\r\n" +
                    "          DocStatus=document.getElementById('drpSelectDocStatus').value;\r\n" +
                    "      }\r\n" +

                    "      ReleaseDate='';\r\n" +
                    "      if(document.getElementById('txtReleaseDate')!=null)\r\n" +
                    "      {\r\n" +
                    "          ReleaseDate=document.getElementById('txtReleaseDate').value;\r\n" +
                    "      }\r\n" +

                    "      EffectedDate='';\r\n" +
                    "      if(document.getElementById('txtEffectedDate')!=null)\r\n" +
                    "      {\r\n" +
                    "          EffectedDate=document.getElementById('txtEffectedDate').value;\r\n" +
                    "      }\r\n" +

                    "      EndEffectedDate='';\r\n" +
                    "      if(document.getElementById('txtEndEffectedDate')!=null)\r\n" +
                    "      {\r\n" +
                    "          EndEffectedDate=document.getElementById('txtEndEffectedDate').value;\r\n" +
                    "      }\r\n" +

                    "      SignDate='';\r\n" +//ngày đăng Công báo
                    "      if(document.getElementById('txtSignDate')!=null)\r\n" +
                    "      {\r\n" +
                    "          SignDate=document.getElementById('txtSignDate').value;\r\n" +
                    "      }\r\n" +

                    "      ReplaceDoc='';\r\n" +
                    "      if(document.getElementById('txtReplaceDoc')!=null)\r\n" +
                    "      {\r\n" +
                    "          ReplaceDoc=document.getElementById('txtReplaceDoc').value;\r\n" +
                    "      }\r\n" +

                    "      ModifyDoc='';\r\n" +
                    "      if(document.getElementById('txtModifyDoc')!=null)\r\n" +
                    "      {\r\n" +
                    "          ModifyDoc=document.getElementById('txtModifyDoc').value;\r\n" +
                    "      }\r\n" +


                    "      IsNew = document.getElementById('drpSelectIsNew').value;\r\n" +
                    "      Searchable=0;\r\n" +
                    "      if(document.getElementById('drpSelectSearchable')!=null)\r\n" +
                    "      {\r\n" +
                    "          Searchable=document.getElementById('drpSelectSearchable').value;\r\n" +
                    "      }\r\n" +


                    "      var startIndex = document.getElementById('hdRelationTypeDocStart').value;\r\n" +
                    "      var endIndex = document.getElementById('hdRelationTypeDocEnd').value;\r\n" +
                    "      var arr = []; \r\n" +
                    "      for(var index = startIndex; index < endIndex; index++) { \r\n" +
                    "          arr.push(document.getElementById('txtRelationTypeText_'+index).value);// + '_X_';  \r\n" +
                    "      } \r\n" +


                    "      WorkflowDefId=document.getElementById('txtWorkflowDefId').value;\r\n" +
                    "      DataLanguage=document.getElementById('txtDataLanguage').value;\r\n" +

                    "      AjaxOut = Portal.Cms.Render.AddCmsDocumentDataRenderBll.ServerSideAdd(SiteId, WorkflowDefId, DataLanguage, DataId, GroupDataId, ParentDataId, Alias, Subject, Description, UploadFile,  DocType,DocField, DocReleaseFrom,DocSigner,DocStatus,SignDate, ReleaseDate,EffectedDate,EndEffectedDate,ReplaceDoc,ModifyDoc, IsNew, Searchable, arr).value;\r\n" +
                    "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='';\r\n" +
                    "      if(AjaxOut.Error)\r\n" +
                    "      {\r\n" +
                    "          alert(AjaxOut.InfoMessage);\r\n" +
                    "          return;\r\n" +
                    "      }\r\n" +
                    "      if(AjaxOut.RetUrl!='')\r\n" +
                    "      {\r\n" +
                    "          window.open(AjaxOut.RetUrl,'_self');\r\n" +
                    "      }\r\n" +
                    "      else\r\n" +
                    "      {\r\n" +
                    "          document.getElementById('divListForm').innerHTML = AjaxOut.HtmlContent;\r\n" +
                    "          ClientBack();\r\n" +
                    "      }\r\n" +
                    "  }\r\n" +


                    "function fileSelected() {\r\n" +
                    "    var file = document.getElementById('fileToUpload').files[0];\r\n" +
                    "    if (file) {\r\n" +

                    "        var ext = file.name.split('.').pop();" +
                    //"        alert(ext);" +
                    //"        if(ext!='pdf' || ext!='docx' || ext!='doc') \r\n" +
                    "        if(ext=='PDF'||ext=='pdf'||ext=='docx'||ext=='doc') \r\n" +
                    "        {\r\n" +
                    //"           alert('Chỉ chấp nhận file đính kèm là Word và Pdf!'); \r\n" +
                    //"           return; \r\n" +                    
                    "        var fileSize = 0;\r\n" +
                    "        if (file.size > 1024 * 1024)\r\n" +
                    "            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n" +
                    "        else\r\n" +
                    "            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n" +
                    "        document.getElementById('fileName').innerHTML = 'Tên tệp: ' + file.name;\r\n" +
                    "        document.getElementById('fileSize').innerHTML = 'Kích cỡ: ' + fileSize;\r\n" +
                    "        document.getElementById('fileType').innerHTML = 'Loại tệp: ' + file.type;\r\n" +
                    //"    var fd = new FormData();\r\n" +
                    //"    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                    //"    var xhr = new XMLHttpRequest();\r\n" +
                    //"    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                    //"    xhr.addEventListener(\"load\", uploadCompletePreview, false);\r\n" +
                    ////"    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                    ////"    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                    //"    xhr.open(\"POST\", \"CmsUploadPreviewHandler.ashx?sid=" + SiteId + "\");\r\n" +
                    //"    xhr.send(fd);\r\n" +
                    // "        document.getElementById('fileImageUrl').innerHTML = '<img src='+file.fileName+'>';\r\n" +

                    "        }\r\n" +
                    "        else {\r\n" +
                    "           alert('Hệ thống chỉ chấp nhận file đính kèm là Word và Pdf!'); \r\n" +
                    "           return; \r\n" +                    
                    "        }\r\n" +
                     "    }\r\n" +
                     "}\r\n" +

                     "function uploadFile() {\r\n" +
                     "    if(document.getElementById('fileToUpload').value==''){\r\n" +
                     "       CallSaveAddData();\r\n" +
                     "       return;\r\n" +
                     "   }\r\n" +
                     "    DataId=document.getElementById('txtDataId').value;\r\n" +
                     "    var file = document.getElementById('fileToUpload').files[0];\r\n" +

                     "    if (file) {\r\n" +
                     "        var ext = file.name.split('.').pop();" +                    
                     "        if(ext=='PDF'||ext=='pdf'||ext=='docx'||ext=='doc') \r\n" +
                     "        {\r\n" +
                     "        var fileSize = 0;\r\n" +
                     "        if (file.size > 1024 * 1024)\r\n" +
                     "          {\r\n" +
                     "              fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n" +                     
                     "              if((Math.round(file.size * 100 / (1024 * 1024)) / 100)>32)\r\n" +
                     "              {\r\n" +
                     "                  alert('Hệ thống chỉ cho phép tải file đính kèm tối đa 32MB!');\r\n" +
                     "                  return; \r\n" +
                     "              }\r\n" +
                     "         }\r\n" +
                     "        else\r\n" +
                     "            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n" +

                     "    var fd = new FormData();\r\n" +
                     "    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                     "    var xhr = new XMLHttpRequest();\r\n" +
                     "    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                     "    xhr.addEventListener(\"load\", uploadComplete, false);\r\n" +
                     "    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                     "    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                     "    xhr.open(\"POST\", \"" + UploadHandler + "?sid=" + SiteId + "&uni=" + WebSessionUtility.GetCurrentLoginUser().AssetCode + "&gid=" + GroupDataId + "&dataid=" + NewDataId + "\");\r\n" +
                     "    xhr.send(fd);\r\n" +
                     "          }\r\n" +
                     "        else {\r\n" +
                     "           alert('Hệ thống chỉ chấp nhận file đính kèm là Word và Pdf!'); \r\n" +
                     "           return; \r\n" +
                     "        }\r\n" +
                     "      }\r\n" +
                     "}\r\n" +

                     "function uploadProgress(evt) {\r\n" +
                     "    if (evt.lengthComputable) {\r\n" +
                     "    }\r\n" +
                     "    else {\r\n" +
                     "        document.getElementById('progressNumber').innerHTML = 'Không tính toán được thời gian';\r\n" +
                     "    }\r\n" +
                     "}\r\n" +


                     "function uploadCompletePreview(evt) {\r\n" +
                    //"        document.getElementById('fileImageUrl').innerHTML = evt.target.responseText;\r\n" +
                     "}\r\n" +


                     "function uploadComplete(evt) {\r\n" +
                     "    /* This event is raised when the server send back a response */\r\n" +
                     "  if(evt.target.responseText.indexOf('ERROR')!=-1)\r\n" +
                     "  {\r\n" +
                     "      alert(evt.target.responseText.substring(6));\r\n" +
                     "      return;\r\n" +
                     "  }\r\n" +
                     
                     "    document.getElementById('txtUploadFile').value=evt.target.responseText;\r\n" +
                     "    //doan nay chay upload vao day...\r\n" +
                     "    CallSaveAddData();\r\n" +
                     "   }\r\n" +

                       "function uploadFailed(evt) {\r\n" +
                     "       alert(\"Lỗi khi tải tệp dữ liệu lên máy chủ.\");\r\n" +
                     "   }\r\n" +

                     "   function uploadCanceled(evt) {\r\n" +
                     "        alert(\"Người dùng hủy bỏ tải lên máy chủ hoặc mất kết nối với máy chủ.\");\r\n" +
                     "   }\r\n" +


                   "  </script>\r\n";


                string SelectIsNew = " <select id=\"drpSelectIsNew\">\r\n" +
                     "      <option value=\"0\">Tài liệu bình thường</option>\r\n" +
                     "      <option value=\"1\" selected>Tài liệu mới</option>\r\n" +
                     " </select>\r\n";


                string SelectSearchable =
                    " <select id=\"drpSelectSearchable\">\r\n" +
                    "      <option value=\"0\">Không tìm kiếm toàn văn được</option>\r\n" +
                    "      <option value=\"1\" selected>Tìm kiếm toàn văn được</option>\r\n" +
                    " </select>\r\n";

                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonRoot = WebConfig.GetButtonIconRoot(OSiteParam);


                Html +=
                   " <input id=txtWorkflowDefId type=hidden value=\"" + WorkflowDefId + "\">\r\n" +
                   " <input id=txtDataLanguage type=hidden value=\"" + DataLanguage + "\">\r\n" +
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   "            <li onclick=\"javascript:uploadFile();\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                   "            <li onclick=\"" + BackScript + "\"><img class=image src=\"" + ButtonRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "<div class=CssFormSaveUpdate>\r\n" +
                   "  <input type=hidden id=txtDataId value=\"" + NewDataId + "\">\r\n" +
                   "  <div id=divCallSaveAddDataProcessing class=CssProcessing></div>\r\n" +
                   "  <table>\r\n" +
                   "    <tr class=\"CssRowAlias\">\r\n" +
                   "        <td class=c1>Số văn bản:" + Utility.fieldRequired + "</td>\r\n" +
                   "        <td class=c2><input id=txtAlias value=\"\" class=textbox type=textbox></td>\r\n" +
                   "    </tr>\r\n" +
                   "    <tr class=\"CssRowSubject\">\r\n" +
                   "        <td class=c1>Trích yếu:" + Utility.fieldRequired + "</td>\r\n" +
                   "        <td class=c2><textarea type=textarea class=textarea id=\"txtSubject\" name=\"txtSubject\"></textarea></td>\r\n" +
                   "    </tr>\r\n";
                //"    <tr class=\"CssRowDescription\" stlye=\"display:none;\">\r\n" +
                //"        <td class=c1 style=\"vertical-align:top;\">Mô tả:</td>\r\n" +
                //"        <td class=c2>\r\n" +
                // "               <textarea type=textarea class=textarea id=\"txtDescription\" name=\"txtDescription\"></textarea>\r\n" +
                //"        </td>\r\n" +
                //"    </tr>\r\n";

                string SelectDocumentType =
                    "<select id=drpSelectDocType class=drplist>\r\n";
                DocTypeCls[] DocTypes = DocTypeProcessBll.ReadingDocType(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocTypes.Length; iIndex++)
                {
                    SelectDocumentType += "   <option value=\"" + DocTypes[iIndex].DocTypeId + "\">" + DocTypes[iIndex].DocTypeName + "</option>\r\n";
                }
                SelectDocumentType += "</select>\r\n";


                string SelectDocField =
                  "<select id=drpSelectDocField class=drplist>\r\n";
                DocFieldCls[] DocFields = DocFieldProcessBll.ReadingDocField(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocFields.Length; iIndex++)
                {
                    SelectDocField += "   <option value=\"" + DocFields[iIndex].DocFieldId + "\">" + DocFields[iIndex].DocFieldName + "</option>\r\n";
                }
                SelectDocField += "</select>\r\n";

                string SelectDocReleaseFrom =
                    "<select id=drpSelectDocReleaseFrom class=drplist onchange=\"javascript:ClientDocReleaseChange();\">\r\n";
                DocReleaseFromCls[] DocReleaseFroms = DocReleaseFromProcessBll.ReadingDocReleaseFrom(SiteId, GroupDataId);
                string DocReleaseFromsId = string.Empty;
                for (int iIndex = 0; iIndex < DocReleaseFroms.Length; iIndex++)
                {
                    if (DocReleaseFroms[iIndex].SortIndex == 1)
                    {
                        SelectDocReleaseFrom += "   <option selected=\"selected\" value=\"" + DocReleaseFroms[iIndex].DocReleaseFromId + "\">" + DocReleaseFroms[iIndex].DocReleaseFromName + "</option>\r\n";
                        DocReleaseFromsId = DocReleaseFroms[iIndex].DocReleaseFromId;
                    }
                    else
                        SelectDocReleaseFrom += "   <option value=\"" + DocReleaseFroms[iIndex].DocReleaseFromId + "\">" + DocReleaseFroms[iIndex].DocReleaseFromName + "</option>\r\n";
                }
                SelectDocReleaseFrom += "</select>\r\n";

                string SelectDocSigner =
                  "<select id=drpSelectDocSigner class=drplist>\r\n";
                DocSignerCls[] DocSigners = new DocSignerProcessBll().GetDocSingerByGroupReleaseFrom(SiteId, DocReleaseFromsId);
                for (int iIndex = 0; iIndex < DocSigners.Length; iIndex++)
                {
                    SelectDocSigner += "   <option value=\"" + DocSigners[iIndex].DocSignerId + "\">" + DocSigners[iIndex].DocSignerName + "</option>\r\n";
                }
                SelectDocSigner += "</select>\r\n";

                string SelectStatus =
                    "<select id=drpSelectDocStatus class=drplist>\r\n" +
                    "   <option value=\"0\">Hết hiệu lực</option>\r\n" +
                    "   <option value=\"1\" selected=\"selected\">Có hiệu lực</option>\r\n" +
                    "</select>\r\n";

                Html +=
                 "    <tr>\r\n" +
                 "        <td class=c1>Loại văn bản:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocumentType + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Cơ quan ban hành:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocReleaseFrom + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Lĩnh vực:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocField + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Người ký:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocSigner + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Trạng thái:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectStatus + "</td>\r\n" +
                 "    </tr>\r\n" +
                    //"    <tr>\r\n" +
                    //"        <td class=c1>Ngày ký:</td>\r\n" +
                    //"        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtSignDate") + "</td>\r\n" +
                    //"    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày ban hành:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtReleaseDate") + "</td>\r\n" +
                 "    </tr>\r\n" +
                "    <tr>\r\n" +
                "        <td class=c1>Ngày đăng công báo:</td>\r\n" +
                "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtSignDate") + "</td>\r\n" +
                "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày hiệu lực:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtEffectedDate") + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày hết hiệu lực:</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtEndEffectedDate") + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Tìm kiếm toàn văn:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectSearchable + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr class=\"CssRowStatus\">\r\n" +
                 "        <td class=c1>Trạng thái:</td>\r\n" +
                 "        <td class=c2>" + SelectIsNew + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr class=\"CssRowAttachFile\">\r\n" +
                 "         <td class=c1>Tài liệu gắn kèm:" + Utility.fieldRequired + "</td>\r\n" +
                 "         <td><input type=hidden id=\"txtUploadFile\"><input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload\" onchange=\"fileSelected();\" /></td>\r\n" +
                 "    </tr>\r\n" +
                 "       <tr>\r\n" +
                "           <td></td>\r\n" +
                "           <td>\r\n" +
                "               <div id=\"progressNumber\"></div>\r\n" +
                "               <div id=\"fileName\">\r\n" +
                "               </div>\r\n" +
                "               <div id=\"fileSize\">\r\n" +
                "               </div>\r\n" +
                "               <div id=\"fileType\">\r\n" +
                "               </div>\r\n" +
                "               <div id=fileImageUrl></div>\r\n" +
                "           </td>\r\n" +
                "       </tr>\r\n" +
                "  </table>\r\n" +
                "</div>\r\n";

                //relate documents
                Html +=
                    "<div class='RelationDivFunc'>" +
                    "<h3>Các văn bản liên quan</h3> \r\n" +
                    "<Table> \r\n";

                RelationTypeCls[] RelationTypes = RelationTypeProcessBll.ReadingAllRelationType(SiteId);

                for (int iIndex = 0; iIndex < RelationTypes.Length; iIndex++)
                {
                    CmsDataRelationCls[] CmsDataRelations = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingDocumentRelation(SiteId, NewDataId, RelationTypes[iIndex].RelationTypeId);
                    Html +=
                    "<tr> \r\n" +
                    "   <td> \r\n" +
                    "       <span class='docRelation'>- " + RelationTypes[iIndex].RelationTypeName + "</span>\r\n" +
                    "   </td> \r\n" +
                    "</tr> \r\n" +
                    "<tr> \r\n" +
                    "   <td> \r\n" +
                    " <div class=CssRelationDivFunc>Số văn bản: <input type=textbox id=\"txtRelationTypeText_" + RelationTypes[iIndex].SortIndex + "\" class=textbox> \r\n";
                    if (iIndex == 0)
                        Html += "     <input type=hidden id=\"hdRelationTypeDocStart\" value=\"" + RelationTypes[iIndex].SortIndex + "\"> ";
                    if (iIndex == RelationTypes.Length - 1)
                        Html += "     <input type=hidden id=\"hdRelationTypeDocEnd\" value=\"" + RelationTypes[iIndex].SortIndex + "\"> ";
                    Html +=
                    "</div>\r\n" +
                     "   </td> \r\n" +
                    "</tr> \r\n";
                }
                Html += "</table>\r\n" +
                "</div>\r\n";

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerDocReleaseChange(string SiteId, string SelectDocReleaseFrom)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                StringBuilder html = new StringBuilder();
                DocSignerCls[] _DocSignerClss = new DocSignerProcessBll().GetDocSingerByGroupReleaseFrom(SiteId, SelectDocReleaseFrom);
                foreach (DocSignerCls oDocSignerCls in _DocSignerClss)
                {
                    html.Append("<option value=\"" + oDocSignerCls.DocSignerId + "\">" +
                                    oDocSignerCls.DocSignerName +
                                "</option>");
                }
                OAjaxOut.RetObject = _DocSignerClss;
                //OAjaxOut.HtmlContent = html.ToString();

            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideAddRelationList(
            string SiteId,
            string GroupDataId,
            string SrcDataId,
            //string RelationTypeId,
            string[] documentNo,
            string BackAspx)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, SrcDataId);
                if (OCmsData == null)
                {
                    throw new Exception("Số văn bản liên quan không hợp lệ! Không tìm thấy số văn bản này!");
                }
                //if (OCmsData.Equals(SrcDataId))
                //{
                //    throw new Exception("Số văn bản liên quan không hợp lệ! Văn bản liên quan không thể chính là văn bản này!");
                //}

                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).AddDocumentRelationList(SiteId, SrcDataId, documentNo);
                OAjaxOut.RetUrl = "?gid=" + GroupDataId + "&CmsDataId=" + SrcDataId + "&back=" + BackAspx;

            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideAdd(
            string SiteId,
            string WorkflowDefId,
            string DataLanguage,
            string DataId,
            string GroupDataId,
            string ParentDataId,
            string Alias,
            string Subject,
            string Description,
            string UploadFile,
            string DocType,
            string DocField,
            string DocReleaseFrom,
            string DocSigner,
            string DocStatus,
            string SignDate,
            string ReleaseDate,
            string EffectedDate,
            string EndEffectedDate,
            string ReplaceDoc,
            string ModifyDoc,
            int IsNew,
            int AttachedSearchable,
            string[] arrRelationDocType
            //string GroupDataFolderId,
            )
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                //if (string.IsNullOrEmpty(Alias)) Alias = System.Guid.NewGuid().ToString().Substring(0, 8);
                if (string.IsNullOrEmpty(Alias)) throw new Exception("Chưa nhập số văn bản!");
                if (string.IsNullOrEmpty(Subject)) throw new Exception("Chưa nhập trích yếu!");
                //if (string.IsNullOrEmpty(Description)) throw new Exception("Chưa nhập trích yếu!");
                if (string.IsNullOrEmpty(ReleaseDate)) throw new Exception("Chưa nhập ngày ban hành!");
                if (string.IsNullOrEmpty(EffectedDate)) throw new Exception("Chưa nhập ngày hiệu lực!");
                if (string.IsNullOrEmpty(UploadFile)) throw new Exception("Chưa tải tệp đính kèm!");

                if (!string.IsNullOrEmpty(ReleaseDate))
                {
                    if (FunctionUtilities.checkVnDate(ReleaseDate) == false) throw new Exception("Ngày ban hành không hợp lệ!");
                }
                if (!string.IsNullOrEmpty(EffectedDate))
                {
                    if (FunctionUtilities.checkVnDate(EffectedDate) == false) throw new Exception("Ngày hiệu lực không hợp lệ!");
                }
                if (!string.IsNullOrEmpty(EndEffectedDate))
                {
                    if (FunctionUtilities.checkVnDate(EndEffectedDate) == false) throw new Exception("Ngày hết hiệu lực không hợp lệ!");
                }

                if (OGroupData.frkDataTypeId.Equals("document"))
                {
                    WorkflowDefId = WebConfig.WorkFlowId;// "74f46290-df0e-4a46-bc72-c5088b1ea7e0";
                }

                //if (string.IsNullOrEmpty(GroupDataFolderId)) GroupDataFolderId = "";
                //if (GroupDataFolderId.Equals("root")) GroupDataFolderId = "";
                IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
                IDbTransaction Trans = DBService.BeginTransaction();
                try
                {
                    CmsDataCls OCmsData = new CmsDataCls();
                    OCmsData.frkGroupDataId = GroupDataId;
                    OCmsData.ParentDataId = ParentDataId;
                    OCmsData.DataAlias = Alias;
                    OCmsData.Subject = Alias;//số văn bản
                    OCmsData.OtherSubject = "";
                    OCmsData.Description = Subject;// trích yếu
                    OCmsData.Body = Description;//nội dung
                    OCmsData.Source = "";
                    OCmsData.Url = "";
                    OCmsData.Target = "";
                    OCmsData.UploadFile = UploadFile;
                    OCmsData.SortIndex = 0;
                    OCmsData.frkDocTypeId = DocType;
                    OCmsData.frkDocFieldId = DocField;
                    OCmsData.frkDocReleaseFromId = DocReleaseFrom;
                    OCmsData.frkDocSignerId = DocSigner;
                    OCmsData.DocStatus = DocStatus;
                    OCmsData.SignDate = SignDate;
                    OCmsData.ReleaseDate = ReleaseDate;
                    OCmsData.EffectedDate = EffectedDate;
                    OCmsData.EndEffectedDate = EndEffectedDate;
                    OCmsData.ReplaceDoc = ReplaceDoc;
                    OCmsData.ModifyDoc = ModifyDoc;
                    OCmsData.IsNew = IsNew;
                    OCmsData.AttachedSearchable = AttachedSearchable;
                    //OCmsData.frkGroupDataFolderId = GroupDataFolderId;

                    DataId = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).AddCmsData(Trans, SiteId, WorkflowDefId, DataLanguage, DataId, OCmsData, true);
                    if (!string.IsNullOrEmpty(WorkflowDefId))
                    {
                        //khoi tao quy trinh o day...!
                        CmsUtility.ServerSideStartWorkflow(Trans, SiteId, WorkflowDefId, DataId, "Publishing", OGroupData.frkDataTypeId, "");

                    }

                    Trans.Commit();

                    ServerSideAddRelationList(SiteId, GroupDataId, DataId, arrRelationDocType, string.Empty);


                    OAjaxOut.RetUrl = "PreviewCmsDocumentData.aspx?gid=" + OGroupData.GroupDataId + "&CmsDataId=" + DataId;
                }
                catch (Exception ex)
                {
                    Trans.Rollback();
                    throw (ex);
                }
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

    }
}
